package com.hjs.servlet.dailyinspection.dailyinspectrecording;

import com.hjs.bean.DailyInspectRecording;
import com.hjs.bean.DailyInspecteRecordingCom;
import com.hjs.mapper.DailyInspectRecordingMapper;
import com.hjs.tools.Mapper;
import com.hjs.tools.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * @author violetfreesia
 * @date 2020/06/19
 */
@Slf4j
@WebServlet("/dailyInspection/add")
public class AddDailyInspection extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        RequestUtil requestUtil = new RequestUtil(request, response);
        try (SqlSession sqlSession = Mapper.getSqlSession()) {
            DailyInspectRecording dailyInspectRecording = new DailyInspectRecording(requestUtil.getInt("dailyInspecteID"),
                    null, requestUtil.getString("inspectorID"),null,
                    LocalDateTime.now());
            DailyInspectRecordingMapper mapper = sqlSession.getMapper(DailyInspectRecordingMapper.class);
            boolean sqlResult = mapper.updateOneDailyInspectRecording(dailyInspectRecording);
            if (sqlResult) {
                sqlResult = addAllDailyInspectRecordingCom(requestUtil, mapper, dailyInspectRecording.getDailyInspecteID());
            }
            Mapper.SessionEnd(sqlResult, sqlSession, "添加日常巡检记录表失败");
            requestUtil.responseIsSuccess(sqlResult,"添加失败");
        } catch (Exception e) {
            log.error(e.toString());
            requestUtil.responseFail("未知错误");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {

    }

    private boolean addAllDailyInspectRecordingCom(RequestUtil requestUtil, DailyInspectRecordingMapper mapper, int dailyInspectRecordingId) {
        String[] properties = {"damageTypeID", "damageDescription", "remarks"};
        for (int i = 0; i < requestUtil.getInt("comNumber"); i++) {
            boolean sqlResult = mapper.addOneDailyInspecteRecordingCom(new DailyInspecteRecordingCom(
                    null, dailyInspectRecordingId, requestUtil.getInt(properties[0] + i),
                    requestUtil.getString(properties[1] + i), requestUtil.getString(properties[2] + i)));
            if (!sqlResult)
                return false;
        }
        return true;
    }
}
